package com.example.llm.learn.api.controller;

import com.example.llm.learn.api.dto.CommonResponse;
import com.example.llm.learn.api.dto.UserDTO;
import com.example.llm.learn.api.dto.UserLoginRequestDTO;
import com.example.llm.learn.api.dto.UserTokenDTO;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@CrossOrigin(origins = {"http://localhost:5173", "http://127.0.0.1:5500"})
public class UserController implements InitializingBean {

    private Map<String, UserDTO> userMap = new HashMap<>();

    private Map<String, UserTokenDTO> userTokenMap = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        userMap.put("15712345678", new UserDTO().setId(1L).setName("用户1").setPhone("15712345678").setPassword("123456"));
        userMap.put("15712345679", new UserDTO().setId(2L).setName("用户2").setPhone("15712345679").setPassword("123457"));
        userTokenMap.put("15712345678", new UserTokenDTO("q5fdsgfaedrtvfdgbvfdgd"));
        userTokenMap.put("15712345679", new UserTokenDTO("345fdst34g34t334453rf3"));
    }

    @PostMapping(value = "/user/login")
    public CommonResponse<UserTokenDTO> login(@RequestBody @Validated UserLoginRequestDTO userLoginRequest) {
        if ("25712345678".equals(userLoginRequest.getPhone())) {
            throw new RuntimeException();
        }
        UserDTO userDTO = userMap.get(userLoginRequest.getPhone());
        if (Objects.isNull(userDTO) || !userDTO.getPassword().equals(userLoginRequest.getPassword())) {
            return CommonResponse.error401();
        }
        return CommonResponse.ok(userTokenMap.get(userLoginRequest.getPhone()));
    }

    @GetMapping(value = "/user/userInfo")
    public CommonResponse<UserDTO> userInfo(@RequestParam String phone) {
        return CommonResponse.ok(userMap.get(phone));
    }
}
